<?php

namespace App\Http\Controllers\Site\Custom;

use App\B2BProject\AttachmentPrivateFiles;
use App\B2BProject\Custom\Business\Store;
use App\B2BProject\Custom\Member;
use App\B2BProject\Custom\MemberInformation;
use App\Http\Requests\Register\RegisterProviderMemberRequest;
use App\Http\Requests\Register\RegisterPurchaserMemberRequest;
use App\Http\Requests\Request as FormRequest;
use App\Http\Controllers\Controller;
use DB;
use Exception;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\File\Exception\FileException;
use Throwable;
use App\B2BProject\Site\HelperControllerBuildTrait;
class MemberRegisterController extends Controller
{
    use HelperControllerBuildTrait;
    const PROVIDER_USER  = 1;
    const PURCHASER_USER = 2;

    public function getProvider()
    {
        return view("host/register/provider");
    }
    public function getPurchaser()
    {
        return view("host/register/purchaser");
    }

    public function postPurchaser(RegisterPurchaserMemberRequest $request)
    {
        return $this->register($request, self::PURCHASER_USER);
    }

    public function postProvider(RegisterProviderMemberRequest $request)
    {
        return $this->register($request, self::PROVIDER_USER);
    }

    /**
     * 用户注册过程
     *
     * @param FormRequest $request
     * @param             $class
     *
     * @return null|\Symfony\Component\HttpFoundation\Response
     */
    protected function register(FormRequest $request, $class){
        $response = null;

        try {
            // 开启事务
            DB::transaction(function () use ($request, $class, &$response) {
                $route = 'register.' . ($class == 1 ? 'provider' : 'purchaser');
                $spec  = $request->only([
                    'company',
                    'legal',
                    'identification_number',
                    'address',
                    'contact_person',
                    'contact_phone',
                    //                    'contact_email',
                ]);

                $spec['province_id'] = $request->province;
                $spec['city_id']     = $request->city;
                $spec['county_id']   = $request->county;

                // 处理上传数据
                try {
                    // 营业执照
                    $businessLicense = $request->file('business_license');

                    // 身份证 A，B 面
                    $id_a = $request->file('legal_identity_a');
                    $id_b = $request->file('legal_identity_b');

                    $spec['business_license'] = AttachmentPrivateFiles::setNewUploadFile($businessLicense,
                        '/business_license')->id;
                    $spec['legal_identity_a'] = AttachmentPrivateFiles::setNewUploadFile($id_a, 'identity')->id;
                    $spec['legal_identity_b'] = AttachmentPrivateFiles::setNewUploadFile($id_b, 'identity')->id;
                } catch (FileException $e) {
                    $response = redirect()->route($route)->withErrors($e->getMessage())->withInput();
                    throw $e;
                }

                // 构造用户基础数据
                $basic             = $request->only(['user', 'password', 'email']);
                $basic['class']    = $class;
                $basic['password'] = \Hash::make($basic['password']);

                $member = Member::create($basic);

                // 关联模型绑定 （用户 —— 用户详细信息）
                $member->information()->save(MemberInformation::create($spec));

                // 供应商注册有以下额外逻辑
                if ($class == self::PROVIDER_USER) {
                    // 处理上传数据
                    try {
                        // 分别处理 税务登记证、组织机构代码、授权书
                        $taxReg               = $request->file('tax_registration');
                        $organizationCodeCert = $request->file('organization_code_cert');
                        $authorizations       = $request->file('authorization');

                        $store = [
                            'tax_registration'       => AttachmentPrivateFiles::setNewUploadFile($taxReg,
                                '/tax_registration')->id,
                            'organization_code_cert' => AttachmentPrivateFiles::setNewUploadFile($organizationCodeCert,
                                '/organization_code_cert')->id,
//                            // 地区
//                            'area_province'          => $request->province,
//                            'area_city'              => $request->city,
//                            'area_county'            => $request->county,
                        ];

                        // 对授权书这种存在多张图片的情况进行处理
                        $authorizationsArray = [];
                        foreach ($authorizations as $authorization) {
                            if (!is_null($authorization)) {
                                $authorizationsArray[] = AttachmentPrivateFiles::setNewUploadFile($authorization,
                                    '/authorization');
                            }
                        }
                    } catch (FileException $e) {
                        $response = redirect()->route($route)->withErrors($e->getMessage())->withInput();
                        throw $e;
                    }

                    // 创建店铺实例
                    $storeInstance = Store::create($store);
                    $storeInstance->mainBrand()->attach(explode(',', $request->input('main_brand')));
                    $storeInstance->mainCategory()->attach(explode(',', $request->input('main_category')));

                    // 处理店铺 LOGO
                    $logo                      = $request->file('store_logo');
                    $path                      = "/data/upload/stores/logo";
                    $target                    = $logo->move(base_path('public' .
                                                                       $path .
                                                                       sprintf("/%s/%s/%s", date('Y', time()),
                                                                           date('m', time()),
                                                                           date('d', time()))),
                        Str::random(16) . '.' . $logo->guessClientExtension());
                    $storeInstance->store_logo = str_replace(base_path('public'), '', $target);

                    foreach ($authorizationsArray as $authorization) {
                        $storeInstance->authorizations()->save($authorization);
                    }

                    $member->store()->save($storeInstance);
                }
            });
        } catch (FileException $e) {
            return $response;
        } catch (Exception $e) {
            return http_output($e->getMessage(), 503, 'errors/503');
        } catch (Throwable $e) {
            return http_output($e->getMessage(), 503, 'errors/503');
        }

        return http_output('success');
    }
}
